package com.example.yt_app.Fragment;



import android.content.Intent;

import android.os.Handler;
import android.os.Message;

import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;

import com.example.yt_app.Activity.FragmentThreeActivity;
import com.example.yt_app.Activity.SetActivity;
import com.example.yt_app.Activity.WeatherWebActivity;
import com.example.yt_app.Fragment.BaseFragment.BaseFragment;

import com.example.yt_app.Fragment.EquipmentFragment.AllSbFragment;
import com.example.yt_app.Fragment.EquipmentFragment.BathroomSbFragment;
import com.example.yt_app.Fragment.EquipmentFragment.HomeSbFragment;
import com.example.yt_app.Fragment.EquipmentFragment.KitchenSbFragment;
import com.example.yt_app.Interface.WeatherService;
import com.example.yt_app.R;
import com.example.yt_app.Urils.AESUtils3;
import com.example.yt_app.Urils.Delay;
import com.example.yt_app.Urils.Json;
import com.example.yt_app.Urils.State;
import com.example.yt_app.Urils.Utils;
import com.example.yt_app.adapter.Equipment;
import com.example.yt_app.adapter.NewsAdapter;
import com.example.yt_app.bean.City_weather.City_weather;
import com.example.yt_app.bean.City_weather.Lives;
import com.example.yt_app.bean.Onenet.Data;
import com.example.yt_app.bean.Onenet.JsonRootBean;
import com.google.android.material.tabs.TabLayout;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;


import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.internal.concurrent.Task;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author geyifeng
 * @date 2017/5/12
 */
@SuppressWarnings("ALL")
public class CategoryThreeFragment extends BaseFragment {
    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R.id.viewPager)
    ViewPager viewPager;

    @BindView(R.id.dingwei)
    TextView city;
    /* 天气*/
    @BindView(R.id.tianqi)
    TextView tianqi;
    //空气
    @BindView(R.id.fengli)
    TextView fengli;
    //温度
    @BindView(R.id.wendu)
    TextView wendu;
    //湿度
    @BindView(R.id.shidu)
    TextView shidu;

    @BindView(R.id.add)
    View add;
    //天气控件
    @BindView(R.id.Weather)
    LinearLayout weather;
    private mHandler mHandler = new mHandler();
//    @BindView(R.id.main_swipe)
//    WaveSwipeRefreshLayout main_swipe;
    private AMapLocationClient mLocationClient=null;
    //声明定位回调监听器
    private AMapLocationClientOption mLocationOption=null;
    private OkHttpClient okHttpClient;
    Request request = new Request.Builder()
            .url("http://restapi.amap.com/v3/weather/weatherInfo?"+"key="+ State.GD_ApiKey +
                     "city="+ State.City)
            .build();
    private ArrayList<Fragment> mFragments;
    private String[] mTabName = {"所有设备","房间","厨房","浴室"};
    private List<String> mTitles;
    int time;
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_three_category;
    }

    @Override
    protected void initView() {

        super.initView();
        for (String s : mTabName) {
            tabLayout.addTab(tabLayout.newTab().setText(s));
        }

        mTitles=new ArrayList<>();
        for(int i=0;i<mTabName.length;i++){
            mTitles.add(mTabName[i]);
        }
        viewPager.setAdapter(new Equipment(getChildFragmentManager(), mFragments,mTitles));
        tabLayout.setupWithViewPager(viewPager);
        okHttpClient = new OkHttpClient();



    }
    @SuppressWarnings("AliDeprecation")
    private class mHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (State.City != "定位"){
                        //工作
                        tianqi.setText(State.tianqi);
                        fengli.setText(State.fengli);
                        wendu.setText(State.wendu);
                        shidu.setText(State.shidu);
                        showMessage("更新位置成功");
                    }
                    else {
                        initMap();
                    }
                    break;

                default:break;
            }
        }
    }
    @Override
    protected void setListener() {
    }


    @OnClick({R.id.add,R.id.Weather})
    public void onClick(View v) {
        switch (v.getId()){
            /**
             *  密码保密
             * */
            case R.id.add:
                Intent Intent = new Intent(getActivity(), SetActivity.class);
                startActivity(Intent);
                break;
            case R.id.Weather:
                Intent weat = new Intent(getActivity(), WeatherWebActivity.class);
                startActivity(weat);
                break;

            default:
                throw new IllegalStateException("Unexpected value: " + v.getId());
        }
    }


    /**
     * 初始数据
     *
     * */
    @Override
    protected void initData() {
        initMap();
        mFragments = new ArrayList<>();
        AllSbFragment all_sbFragment = new AllSbFragment();
        HomeSbFragment home_sbFragment = new HomeSbFragment();
        KitchenSbFragment kitchen_sbFragment = new KitchenSbFragment();
        BathroomSbFragment bathroom_sbFragment = new BathroomSbFragment();

        mFragments.add(all_sbFragment);
        mFragments.add(home_sbFragment);
        mFragments.add(kitchen_sbFragment);
        mFragments.add(bathroom_sbFragment);
        city.setText(State.City);


    }
    /**
     * 定位
     * */
    @SuppressWarnings("AliDeprecation")
    public void initMap() {
        //初始化定位
        mLocationClient=new AMapLocationClient(getActivity());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，AMapLocationMode.Battery_Saving为低功耗模式，AMapLocationMode.Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setNeedAddress(true);//设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setOnceLocation(false);//设置是否只定位一次,默认为false
        mLocationOption.setWifiActiveScan(true);//设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setMockEnable(false);//设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setInterval(15000);//设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setOnceLocation(false);//可选，是否设置单次定位默认为false即持续定位
        mLocationOption.setOnceLocationLatest(false); //可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        mLocationOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mLocationOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();

    }
    public AMapLocationListener mLocationListener=new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    // aMapLocation.getLatitude();//获取纬度
                    // aMapLocation.getLongitude();//获取经度
                    aMapLocation.getAccuracy();//获取精度信息
                    java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    //  aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                    //  aMapLocation.getCountry();//国家信息
                    //  aMapLocation.getProvince();//省信息
                    //  aMapLocation.getCity();//城市信息
                    //   aMapLocation.getDistrict();//城区信息
                    //    aMapLocation.getStreet();//街道信息
                    //     aMapLocation.getStreetNum();//街道门牌号信息
                    //    aMapLocation.getCityCode();//城市编码
                    //     aMapLocation.getAdCode();//地区编码
                    System.out.println("所在城市："+aMapLocation.getCountry()+aMapLocation.getProvince()+aMapLocation.getCity());
                    mLocationClient.stopLocation();//停止定位
                    State.City = aMapLocation.getCity();
                    city.setText(State.City);
                    getAsync();
                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("info", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
        }
    };


    /**
     * 获取网络数据
     * */
    @OnClick(R.id.dingwei)
    public void getAsync(){
        Message message = Message.obtain();
        Request request = new Request.Builder()
                .url("http://restapi.amap.com/v3/weather/weatherInfo?"+"key="+ State.GD_ApiKey +
                        "&" + "city="+ State.City)
                .build();
        Call call =okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                try {
           /*         response.body().string()中的 (.string)只能使用一次*/
                    String responseData = response.body().string();
                    City_weather city_weather = Json.gson.fromJson(responseData, City_weather.class);
                    List<Lives> city_weatherData = (List<Lives>) city_weather.getLives();

                    State.wendu = city_weatherData.get(0).getTemperature()+"℃";
                    State.shidu = city_weatherData.get(0).getHumidity()+"%RH";
                    State.fengli = city_weatherData.get(0).getWinddirection()+city_weatherData.get(0).getWindpower();
                    State.tianqi = city_weatherData.get(0).getWeather();
                    System.out.println(State.fengli);
                    System.out.println(State.tianqi);
                    message.what = 0;
                    mHandler.sendMessage(message);

                } catch (IOException e){
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //销毁
        if (mLocationClient !=null){

            mLocationClient.onDestroy();
        }

    }



}
